var createError = require('http-errors');
var express = require('express');

var expressWs = require('express-ws');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mount = require('mount-routes')
const bodyParser = require('body-parser');

let seq = require("./utils/db_config.js")
require('./models.js')

seq.authenticate().then(() => {
  console.log('auth ok')
}).catch(() => {
  console.log('auth err')
})

// 执行同步
// force: true 如果数据库中存在这个表，就先把它删掉
seq.sync({ alter: true }).then(() => {
  console.log('sync ok');
}).catch((err) => {
  console.log(err);
})

var app = express();
app.use(bodyParser.json());//数据JSON类型
app.use(bodyParser.urlencoded({ extended: false }));//解析post请求数据
// 设置跨域和相应数据格式
app.all('/api/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS,PATCH')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method == 'OPTIONS')
    res.sendStatus(200)
  /*让options请求快速返回*/ else next()
})

// 初始化统一响应机制
var resextra = require('./modules/resextra')
app.use(resextra)

//校验是否有token值
var tokenCertification = require('./modules/tokenCertification')
app.use(tokenCertification)


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads/video', express.static('uploads/video'))
app.use('/uploads/imgs', express.static('uploads/imgs'))



var http = require('http');
var server = http.createServer(app);



//路由设置
mount(app, path.join(process.cwd(), '/routes'), true)


app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.sendStatus(500)
});

server.listen('3000')
module.exports = server
console.log("服务器启动,监听地址端口为：localhost:3000");

